package com.changgou.web.order.controller;

import com.changgou.entity.Result;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.order.pojo.OrderItem;
import com.changgou.user.feign.UserFeign;
import com.changgou.user.pojo.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Author LQQ
 * @Date 2020/3/12 15:14
 * @Version 1.0
 */

/**
 * 购物车结算页面渲染,跳转
 */
@Controller
@RequestMapping("/worder")
public class OrderController {
    @Autowired
    private OrderFeign orderFeign;
    @Autowired
    private UserFeign userFeign;

    // @GetMapping("/list")
    @RequestMapping("/ready/order")
    public String readyOrder(Model model) {
        //1. 获取收件人的地址信息
        List<Address> addressList = userFeign.list().getData();

        model.addAttribute("address", addressList);

        //2. 购物车信息
        Map map = orderFeign.list();

        //2.1 map里封装了购物车的列表数据,总数量,总金额
        List<OrderItem> orderItemList = (List<OrderItem>) map.get("orderItemList");

        Integer totalMoney = (Integer) map.get("totalMoney");

        Integer totalNum = (Integer) map.get("totalNum");

        //3.封装
        model.addAttribute("carts", orderItemList);
        model.addAttribute("totalMoney", totalMoney);
        model.addAttribute("totalNum", totalNum);

        //加载默认收件人信息
        for (Address address : addressList) {

            if ("1".equals(address.getIsDefault())) {
                //默认收件人
                model.addAttribute("deAddr", address);
                break;
            }


        }

        return "order";
    }


    /**
     * 后端保存订单
     *
     * @param order
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody Order order) {
        //调用订单服务中添加订单的方法
        Result result = orderFeign.add(order);

        return result;

    }

    /**
     * 选择支付方式的页面
     * @param orderId
     * @param model
     * @return
     */
    @GetMapping("/toPayPage")
    public String toPayPage(String orderId,Model model) {

        Order order = orderFeign.findById(orderId).getData();

        model.addAttribute("orderId",orderId);

        model.addAttribute("payMoney",order.getPayMoney());
        //跳转到选择支付页面
        return "pay";
    }

}
